package net.alpenviewer.app;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * String utilities.
 */
public final class StringUtil {

	private StringUtil() {
		//
	}


	/**
	 * Append all given objects as string together.
	 * The object is evaluated by <code>StringBuilder</code> as well as <code>String.valueOf</code>.
	 * @param args objects to append in a string.
	 * @return result string.
	 */
	public static String append(Object... args) {
		StringBuilder m = new StringBuilder();

		for (Object o : args) {
			m.append(o);
		}

		return m.toString();
	}

	/**
	 * Read file into String.
	 * @param f
	 * 			file
	 * @return String of the file content
	 * @throws IOException
	 */
	public static String readFileIntoString(File f) throws IOException {
		FileInputStream stream = new FileInputStream(f);
		try {
			FileChannel fc = stream.getChannel();
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
			/* Instead of using default, pass in a decoder. */
			return Charset.defaultCharset().decode(bb).toString();
		}
		finally {
			stream.close();
		}
	}
	
	/**
	 * Write content into file.
	 * @param f
	 * 			file to write
	 * @param s
	 * 			content in String
	 */
	public static void writeStringIntoFile(File f, String s) {
	
		Writer output = null;
		try {
			output = new BufferedWriter(new FileWriter(f));
		    output.write(s);	
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
		
	}
	
	public static String encodeUrlString(String string) {
		try {
			return URLEncoder.encode(string, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException(e);
		}
	}

	public static String decodeUrlString(String string) {
		try {
			return URLDecoder.decode(string, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalArgumentException(e);
		}
	}
}
